package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author atguigu-mqx
 * @ClassName AlbumReceiver
 * @description: TODO
 * @date 2024年09月29日
 * @version: 1.0
 */
@Component
public class AlbumReceiver {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AlbumInfoService albumInfoService;

    /**
     * 监听播放统计消息
     * @param msg
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void trackStatUpdate(String msg, Message message , Channel channel){
        //  判断当前这个对象是否存在！
        try {
            if (!StringUtils.isEmpty(msg)){
                //  需要将这个字符串转为TrackStatMqVo
                TrackStatMqVo trackStatMqVo = JSON.parseObject(msg, TrackStatMqVo.class);
                //  获取业务编号
                String businessNo = trackStatMqVo.getBusinessNo();
                //  使用setnx;
                Boolean result = redisTemplate.opsForValue().setIfAbsent(businessNo, "1", 10, TimeUnit.MINUTES);
                if (result){
                    try {
                        //  说明是第一次消费消息;
                        albumInfoService.trackStatUpdate(trackStatMqVo);
                    } catch (Exception e) {
                        //  删除数据
                        this.redisTemplate.delete(businessNo);
                        //  重试发送消息 利用redis 做重试次数限制;
                        channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                        System.out.println(e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //  收到确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
